package com.ruoyi.ap.service.impl;

import com.ruoyi.ap.domain.Farmer;
import com.ruoyi.ap.mapper.FarmerMapper;
import com.ruoyi.ap.pojo.vo.FarmerVo;
import com.ruoyi.ap.service.IFarmerService;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 农户Service业务层处理
 * 
 * @author HuaQP
 * @date 2023-09-11
 */
@Service
public class FarmerServiceImpl implements IFarmerService 
{
    @Resource
    private FarmerMapper farmerMapper;

    /**
     * 查询农户
     * 
     * @param id 农户主键
     * @return 农户
     */
    @Override
    public Farmer selectFarmerById(Long id)
    {
        return farmerMapper.selectFarmerById(id);
    }

    /**
     * 查询农户列表
     * 
     * @param farmerVo 农户
     * @return 农户
     */
    @Override
    public List<FarmerVo> selectFarmerVoList(FarmerVo farmerVo)
    {
        return farmerMapper.selectFarmerVoList(farmerVo);
    }

    /**
     * 新增农户
     * 
     * @param farmer 农户
     * @return 结果
     */
    @Override
    public int insertFarmer(Farmer farmer)
    {
        farmer.setCreateTime(DateUtils.getNowDate());
        return farmerMapper.insertFarmer(farmer);
    }

    /**
     * 修改农户
     * 
     * @param farmer 农户
     * @return 结果
     */
    @Override
    public int updateFarmer(Farmer farmer)
    {
        farmer.setUpdateTime(DateUtils.getNowDate());
        return farmerMapper.updateFarmer(farmer);
    }

    /**
     * 批量删除农户
     * 
     * @param ids 需要删除的农户主键
     * @return 结果
     */
    @Override
    public int deleteFarmerByIds(Long[] ids)
    {
        return farmerMapper.deleteFarmerByIds(ids);
    }

    /**
     * 删除农户信息
     * 
     * @param id 农户主键
     * @return 结果
     */
    @Override
    public int deleteFarmerById(Long id)
    {
        return farmerMapper.deleteFarmerById(id);
    }

    // 查询农户树结构信息
    @Override
    public List<TreeSelect> selectFarmerTreeList() {
        FarmerVo farmerVo = new FarmerVo();
        List<FarmerVo> farmerVoList = farmerMapper.selectFarmerVoList(farmerVo);

        //村庄列表
        List<TreeSelect> listTree = farmerVoList.stream().map(item->new TreeSelect(item.getVillageId(),item.getVillageName()))
            .collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        //每个村庄中的农户生成农户叶节点
        for (TreeSelect node : listTree) {
            for (FarmerVo item : farmerVoList) {
               if(node.getId().equals(item.getVillageId())){
                   node.getChildren().add(new TreeSelect(item.getId(),item.getName()));
               }
            }
        }
        return listTree;
    }
}
